<template>
  <div class="chat-container">
    <div class="chat-layout">
      <!-- 左侧边栏 - 会话列表 -->
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h2>聊天</h2>
          <button class="btn-primary small" @click="createPrivateChat">
            <i class="fas fa-plus"></i>
          </button>
        </div>
        
        <div class="sidebar-search">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索会话..."
          />
        </div>
        
        <div class="chat-tabs">
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'rooms' }"
            @click="activeTab = 'rooms'"
          >
            房间
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'private' }"
            @click="activeTab = 'private'"
          >
            私聊
          </button>
        </div>
        
        <div class="chat-list" ref="chatList">
          <!-- 房间列表 -->
          <div v-if="activeTab === 'rooms'">
            <div 
              v-for="room in filteredRooms" 
              :key="room.id"
              class="chat-item"
              :class="{ active: selectedRoom?.id === room.id }"
              @click="selectRoom(room)"
            >
              <div class="chat-avatar">
                <i class="fas fa-users"></i>
              </div>
              <div class="chat-info">
                <div class="chat-name">{{ room.name }}</div>
                <div class="chat-preview">
                  <span v-if="room.lastMessage?.senderId !== currentUser?.id" class="sender">
                    {{ getSenderName(room.lastMessage?.senderId) }}: 
                  </span>
                  <span class="message-text">{{ room.lastMessage?.content || '暂无消息' }}</span>
                </div>
              </div>
              <div class="chat-meta">
                <div class="message-time">{{ formatTime(room.lastMessage?.createdAt) }}</div>
                <div v-if="room.unreadCount > 0" class="unread-badge">{{ room.unreadCount }}</div>
              </div>
            </div>
          </div>
          
          <!-- 私聊列表 -->
          <div v-else-if="activeTab === 'private'">
            <div 
              v-for="chat in filteredPrivateChats" 
              :key="chat.userId"
              class="chat-item"
              :class="{ active: selectedChat?.userId === chat.userId }"
              @click="selectPrivateChat(chat)"
            >
              <div class="chat-avatar">
                <img :src="chat.avatar || 'https://via.placeholder.com/40'" alt="Avatar" />
              </div>
              <div class="chat-info">
                <div class="chat-name">{{ chat.nickname || chat.username }}</div>
                <div class="chat-preview">
                  <span v-if="chat.lastMessage?.senderId !== currentUser?.id" class="sender">
                    {{ getSenderName(chat.lastMessage?.senderId) }}: 
                  </span>
                  <span class="message-text">{{ chat.lastMessage?.content || '暂无消息' }}</span>
                </div>
              </div>
              <div class="chat-meta">
                <div class="message-time">{{ formatTime(chat.lastMessage?.createdAt) }}</div>
                <div v-if="chat.unreadCount > 0" class="unread-badge">{{ chat.unreadCount }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧主聊天区域 -->
      <div class="chat-main" v-if="selectedRoom || selectedChat">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-partner-info">
            <div class="partner-avatar">
              <i v-if="selectedRoom" class="fas fa-users"></i>
              <img v-else-if="selectedChat" :src="selectedChat.avatar || 'https://via.placeholder.com/40'" alt="Avatar" />
            </div>
            <div class="partner-details">
              <div class="partner-name">
                {{ selectedRoom?.name || (selectedChat?.nickname || selectedChat?.username) }}
              </div>
              <div class="partner-status" v-if="selectedChat">
                <span :class="{ online: selectedChat.isOnline }" class="status-dot"></span>
                <span>{{ selectedChat.isOnline ? '在线' : '离线' }}</span>
              </div>
            </div>
          </div>
          
          <div class="chat-actions">
            <button class="action-btn" title="查看信息">
              <i class="fas fa-info-circle"></i>
            </button>
            <button class="action-btn" title="设置">
              <i class="fas fa-cog"></i>
            </button>
          </div>
        </div>
        
        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 消息列表 -->
          <div 
            v-for="message in currentMessages"
            :key="message.id"
            class="message-wrapper"
            :class="{ 'own-message': message.senderId === currentUser?.id }"
          >
            <div v-if="message.senderId !== currentUser?.id" class="message-avatar">
              <img :src="getUserAvatar(message.senderId) || 'https://via.placeholder.com/32'" alt="Avatar" />
            </div>
            <div class="message-content" :class="{ 'own': message.senderId === currentUser?.id }">
              <div v-if="message.senderId !== currentUser?.id" class="message-sender">
                {{ getSenderName(message.senderId) }}
              </div>
              <div class="message-bubble">
                <span v-if="message.type === 'text'" class="message-text">{{ message.content }}</span>
                <img v-else-if="message.type === 'image'" :src="message.content" alt="Image" class="message-image" />
                <div v-else-if="message.type === 'system'" class="system-message">{{ message.content }}</div>
              </div>
              <div class="message-time">{{ formatTime(message.createdAt) }}</div>
            </div>
            <div v-if="message.senderId === currentUser?.id" class="message-avatar own">
              <img :src="currentUser?.avatar || 'https://via.placeholder.com/32'" alt="Avatar" />
            </div>
          </div>
        </div>
        
        <!-- 消息输入区域 -->
        <div class="chat-input-area">
          <div class="input-tools">
            <button class="tool-btn" title="发送图片">
              <i class="fas fa-image"></i>
            </button>
            <button class="tool-btn" title="发送表情">
              <i class="fas fa-smile"></i>
            </button>
            <button class="tool-btn" title="发送文件">
              <i class="fas fa-paperclip"></i>
            </button>
          </div>
          
          <div class="input-container">
            <input
              type="text"
              v-model="messageInput"
              placeholder="输入消息..."
              @keyup.enter="sendMessage"
              :disabled="isLoading"
            />
            <button 
              class="send-btn" 
              @click="sendMessage"
              :disabled="!messageInput.trim() || isLoading"
            >
              <i class="fas fa-paper-plane"></i>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 选择聊天提示 -->
      <div class="chat-empty" v-else>
        <div class="empty-content">
          <i class="fas fa-comments"></i>
          <h3>选择一个聊天</h3>
          <p>从左侧列表选择一个房间或联系人开始聊天</p>
        </div>
      </div>
    </div>
    
    <!-- 创建私聊弹窗 -->
    <div v-if="showCreatePrivateChatModal" class="modal-overlay" @click.self="closeCreatePrivateChatModal">
      <div class="modal-content">
        <h3>创建私聊</h3>
        <div class="modal-search">
          <input
            type="text"
            v-model="privateChatSearch"
            placeholder="搜索用户..."
          />
        </div>
        <div class="user-list">
          <div 
            v-for="user in filteredUsers"
            :key="user.id"
            class="user-item"
            @click="startPrivateChat(user)"
          >
            <div class="user-avatar">
              <img :src="user.avatar || 'https://via.placeholder.com/40'" alt="Avatar" />
              <span :class="{ online: user.isOnline }" class="status-dot"></span>
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.nickname || user.username }}</div>
              <div class="user-status">{{ user.status || '在线' }}</div>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-outline" @click="closeCreatePrivateChatModal">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import userService from '../services/userService';
import chatService from '../services/chatService';
import type { User, ChatRoom, PrivateChat, ChatMessage } from '../types';

const router = useRouter();

// 当前用户信息
const currentUser = ref<User | null>(null);

// 聊天状态
const activeTab = ref<'rooms' | 'private'>('rooms');
const searchQuery = ref('');
const privateChatSearch = ref('');
const messageInput = ref('');
const isLoading = ref(false);

// 选择的聊天
const selectedRoom = ref<ChatRoom | null>(null);
const selectedChat = ref<PrivateChat | null>(null);
const currentMessages = ref<ChatMessage[]>([]);

// 弹窗状态
const showCreatePrivateChatModal = ref(false);

// 聊天列表数据（模拟）
const rooms = ref<ChatRoom[]>([
  {
    id: '1',
    name: '海龟汤爱好者',
    lastMessage: {
      id: '101',
      senderId: '2',
      content: '大家好，有人想一起玩海龟汤吗？',
      type: 'text',
      createdAt: new Date(Date.now() - 1000 * 60 * 5)
    },
    unreadCount: 3,
    users: 15
  },
  {
    id: '2',
    name: '恐怖主题房',
    lastMessage: {
      id: '102',
      senderId: '3',
      content: '这个汤底太恐怖了！',
      type: 'text',
      createdAt: new Date(Date.now() - 1000 * 60 * 15)
    },
    unreadCount: 0,
    users: 8
  },
  {
    id: '3',
    name: '新手教学',
    lastMessage: {
      id: '103',
      senderId: '1',
      content: '欢迎新加入的朋友！',
      type: 'text',
      createdAt: new Date(Date.now() - 1000 * 60 * 30)
    },
    unreadCount: 0,
    users: 12
  }
]);

// 私聊列表数据（模拟）
const privateChats = ref<PrivateChat[]>([
  {
    userId: '2',
    username: 'player2',
    nickname: '汤面达人',
    avatar: 'https://via.placeholder.com/40',
    isOnline: true,
    lastMessage: {
      id: '201',
      senderId: '2',
      content: '明天一起玩海龟汤吧？',
      type: 'text',
      createdAt: new Date(Date.now() - 1000 * 60 * 2)
    },
    unreadCount: 1
  },
  {
    userId: '3',
    username: 'player3',
    nickname: '推理高手',
    avatar: 'https://via.placeholder.com/40',
    isOnline: false,
    lastMessage: {
      id: '202',
      senderId: '1',
      content: '我已经解出来了！',
      type: 'text',
      createdAt: new Date(Date.now() - 1000 * 60 * 60 * 2)
    },
    unreadCount: 0
  }
]);

// 用户列表数据（模拟）
const users = ref<User[]>([
  {
    id: '2',
    username: 'player2',
    nickname: '汤面达人',
    avatar: 'https://via.placeholder.com/40',
    isOnline: true,
    status: '正在聊天'
  },
  {
    id: '3',
    username: 'player3',
    nickname: '推理高手',
    avatar: 'https://via.placeholder.com/40',
    isOnline: false,
    status: '离线'
  },
  {
    id: '4',
    username: 'player4',
    nickname: '新手指引',
    avatar: 'https://via.placeholder.com/40',
    isOnline: true,
    status: '在线'
  },
  {
    id: '5',
    username: 'player5',
    nickname: '恐怖爱好者',
    avatar: 'https://via.placeholder.com/40',
    isOnline: true,
    status: '正在玩游戏'
  }
]);

// 过滤后的房间列表
const filteredRooms = computed(() => {
  if (!searchQuery.value.trim()) {
    return rooms.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return rooms.value.filter(room => 
    room.name.toLowerCase().includes(query) ||
    (room.lastMessage?.content && room.lastMessage.content.toLowerCase().includes(query))
  );
});

// 过滤后的私聊列表
const filteredPrivateChats = computed(() => {
  if (!searchQuery.value.trim()) {
    return privateChats.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return privateChats.value.filter(chat => 
    (chat.nickname && chat.nickname.toLowerCase().includes(query)) ||
    chat.username.toLowerCase().includes(query) ||
    (chat.lastMessage?.content && chat.lastMessage.content.toLowerCase().includes(query))
  );
});

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!privateChatSearch.value.trim()) {
    return users.value.filter(user => user.id !== currentUser?.id);
  }
  
  const query = privateChatSearch.value.toLowerCase();
  return users.value.filter(user => 
    user.id !== currentUser?.id &&
    ((user.nickname && user.nickname.toLowerCase().includes(query)) ||
    user.username.toLowerCase().includes(query))
  );
});

// 加载当前用户信息
const loadCurrentUser = () => {
  currentUser.value = userService.getCurrentUser();
  if (!currentUser.value) {
    router.push('/login');
  }
};

// 选择房间
const selectRoom = async (room: ChatRoom) => {
  selectedRoom.value = room;
  selectedChat.value = null;
  
  // 重置未读消息数
  room.unreadCount = 0;
  
  // 加载房间消息历史
  await loadRoomMessages(room.id);
};

// 选择私聊
const selectPrivateChat = async (chat: PrivateChat) => {
  selectedChat.value = chat;
  selectedRoom.value = null;
  
  // 重置未读消息数
  chat.unreadCount = 0;
  
  // 加载私聊消息历史
  await loadPrivateMessages(chat.userId);
};

// 加载房间消息历史
const loadRoomMessages = async (roomId: string) => {
  isLoading.value = true;
  try {
    // 模拟加载消息历史
    currentMessages.value = [
      {
        id: '301',
        roomId: roomId,
        senderId: '2',
        content: '大家好！',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 6)
      },
      {
        id: '302',
        roomId: roomId,
        senderId: '3',
        content: '你好！有人想一起玩海龟汤吗？',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 5.5)
      },
      {
        id: '303',
        roomId: roomId,
        senderId: '1',
        content: '我想玩！',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 5.2)
      },
      {
        id: '304',
        roomId: roomId,
        senderId: '2',
        content: '大家好，有人想一起玩海龟汤吗？',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 5)
      }
    ];
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('Failed to load room messages:', error);
  } finally {
    isLoading.value = false;
  }
};

// 加载私聊消息历史
const loadPrivateMessages = async (userId: string) => {
  isLoading.value = true;
  try {
    // 模拟加载消息历史
    currentMessages.value = [
      {
        id: '401',
        receiverId: userId,
        senderId: '2',
        content: '嗨，最近玩了什么有趣的海龟汤？',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 3)
      },
      {
        id: '402',
        receiverId: userId,
        senderId: '1',
        content: '我玩了那个"雨夜的哭声"，很不错！',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 2.5)
      },
      {
        id: '403',
        receiverId: userId,
        senderId: '2',
        content: '明天一起玩海龟汤吧？',
        type: 'text',
        createdAt: new Date(Date.now() - 1000 * 60 * 2)
      }
    ];
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('Failed to load private messages:', error);
  } finally {
    isLoading.value = false;
  }
};

// 发送消息
const sendMessage = async () => {
  const content = messageInput.value.trim();
  if (!content || !selectedRoom && !selectedChat || isLoading.value) {
    return;
  }

  isLoading.value = true;
  try {
    let newMessage: ChatMessage;
    
    if (selectedRoom) {
      // 发送房间消息
      newMessage = {
        id: Date.now().toString(),
        roomId: selectedRoom.id,
        senderId: currentUser?.id || '',
        content,
        type: 'text',
        createdAt: new Date()
      };
      
      // 更新房间最后消息
      selectedRoom.lastMessage = newMessage;
    } else if (selectedChat) {
      // 发送私聊消息
      newMessage = {
        id: Date.now().toString(),
        receiverId: selectedChat.userId,
        senderId: currentUser?.id || '',
        content,
        type: 'text',
        createdAt: new Date()
      };
      
      // 更新私聊最后消息
      selectedChat.lastMessage = newMessage;
    }
    
    // 添加到当前消息列表
    if (newMessage) {
      currentMessages.value.push(newMessage);
    }
    
    // 清空输入框
    messageInput.value = '';
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('Failed to send message:', error);
  } finally {
    isLoading.value = false;
  }
};

// 打开创建私聊弹窗
const createPrivateChat = () => {
  showCreatePrivateChatModal.value = true;
  privateChatSearch.value = '';
};

// 关闭创建私聊弹窗
const closeCreatePrivateChatModal = () => {
  showCreatePrivateChatModal.value = false;
};

// 开始私聊
const startPrivateChat = async (user: User) => {
  // 检查是否已存在该用户的私聊
  let existingChat = privateChats.value.find(chat => chat.userId === user.id);
  
  if (!existingChat) {
    // 创建新私聊
    existingChat = {
      userId: user.id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      isOnline: user.isOnline || false,
      lastMessage: null,
      unreadCount: 0
    };
    
    privateChats.value.unshift(existingChat);
  }
  
  // 关闭弹窗
  closeCreatePrivateChatModal();
  
  // 选择该私聊
  await selectPrivateChat(existingChat);
};

// 获取发送者名称
const getSenderName = (senderId?: string): string => {
  if (!senderId) return '未知';
  if (senderId === currentUser?.id) return '我';
  
  // 查找用户
  const user = users.value.find(u => u.id === senderId);
  return user?.nickname || user?.username || '未知用户';
};

// 获取用户头像
const getUserAvatar = (userId?: string): string | undefined => {
  if (!userId) return undefined;
  if (userId === currentUser?.id) return currentUser.avatar;
  
  // 查找用户
  const user = users.value.find(u => u.id === userId);
  return user?.avatar;
};

// 格式化时间
const formatTime = (date?: Date): string => {
  if (!date) return '';
  
  const now = new Date();
  const messageDate = new Date(date);
  
  // 今天的消息，只显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 昨天的消息
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + messageDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 今年的消息，显示月日和时间
  if (messageDate.getFullYear() === now.getFullYear()) {
    return messageDate.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }) + ' ' +
           messageDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 其他年份的消息，显示完整日期和时间
  return messageDate.toLocaleString('zh-CN');
};

// 滚动到底部
const scrollToBottom = () => {
  const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
  if (messagesContainer) {
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }
};

// 生命周期
onMounted(() => {
  loadCurrentUser();
});
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏样式 */
.chat-sidebar {
  width: 320px;
  background-color: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #333;
}

.sidebar-search {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-search input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
  font-size: 0.875rem;
}

.sidebar-search input:focus {
  outline: none;
  border-color: #165DFF;
}

.chat-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
}

.tab-btn {
  flex: 1;
  padding: 0.75rem;
  border: none;
  background-color: white;
  cursor: pointer;
  font-size: 0.875rem;
  color: #666;
  transition: all 0.2s ease;
}

.tab-btn:hover {
  background-color: #f5f5f5;
}

.tab-btn.active {
  color: #165DFF;
  border-bottom: 2px solid #165DFF;
  font-weight: 500;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 1rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
}

.chat-item:hover {
  background-color: #f5f5f5;
}

.chat-item.active {
  background-color: #e6f7ff;
}

.chat-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #e6f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  font-size: 1.25rem;
  color: #165DFF;
  flex-shrink: 0;
}

.chat-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.chat-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 0.25rem;
  font-size: 1rem;
}

.chat-preview {
  font-size: 0.875rem;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-preview .sender {
  font-weight: 500;
}

.chat-meta {
  text-align: right;
  flex-shrink: 0;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
  margin-bottom: 0.25rem;
}

.unread-badge {
  background-color: #ff4d4f;
  color: white;
  font-size: 0.75rem;
  padding: 0.125rem 0.375rem;
  border-radius: 0.75rem;
  font-weight: 500;
  min-width: 18px;
  text-align: center;
}

/* 主聊天区域样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e0e0e0;
}

.chat-partner-info {
  display: flex;
  align-items: center;
}

.partner-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e6f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  font-size: 1.125rem;
  color: #165DFF;
}

.partner-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.partner-details {
  min-width: 0;
}

.partner-name {
  font-weight: 500;
  color: #333;
  font-size: 1rem;
  margin-bottom: 0.25rem;
}

.partner-status {
  display: flex;
  align-items: center;
  font-size: 0.875rem;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  margin-right: 0.5rem;
}

.status-dot.online {
  background-color: #52c41a;
}

.chat-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background-color: #f5f5f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: #e0e0e0;
  color: #333;
}

.chat-messages {
  flex: 1;
  padding: 1.5rem;
  overflow-y: auto;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
}

.message-wrapper.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  max-width: 60%;
}

.message-content.own {
  text-align: right;
}

.message-sender {
  font-size: 0.75rem;
  color: #999;
  margin-bottom: 0.25rem;
  display: inline-block;
}

.message-bubble {
  display: inline-block;
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
  margin-bottom: 0.25rem;
  word-wrap: break-word;
  max-width: 100%;
}

.message-wrapper:not(.own-message) .message-bubble {
  background-color: white;
  border-bottom-left-radius: 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message-wrapper.own-message .message-bubble {
  background-color: #165DFF;
  color: white;
  border-bottom-right-radius: 0;
}

.message-text {
  line-height: 1.4;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 0.25rem;
}

.system-message {
  background-color: #fff7e6;
  color: #fa8c16;
  font-style: italic;
  text-align: center;
  padding: 0.5rem 1rem;
  border-radius: 1rem;
  font-size: 0.875rem;
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}

.chat-input-area {
  padding: 1rem 1.5rem;
  border-top: 1px solid #e0e0e0;
  background-color: white;
}

.input-tools {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.tool-btn {
  width: 36px;
  height: 36px;
  border: none;
  background-color: transparent;
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0.25rem;
  transition: all 0.2s ease;
}

.tool-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

.input-container {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.input-container input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 2rem;
  font-size: 1rem;
}

.input-container input:focus {
  outline: none;
  border-color: #165DFF;
}

.input-container input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.send-btn {
  width: 40px;
  height: 40px;
  border: none;
  background-color: #165DFF;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.send-btn:hover:not(:disabled) {
  background-color: #0e46c2;
  transform: scale(1.1);
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 空聊天提示 */
.chat-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.empty-content {
  text-align: center;
  color: #999;
}

.empty-content i {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-content h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.25rem;
  color: #666;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 0.5rem;
  padding: 1.5rem;
  max-width: 400px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
}

.modal-search {
  margin-bottom: 1rem;
}

.modal-search input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
  font-size: 0.875rem;
}

.modal-search input:focus {
  outline: none;
  border-color: #165DFF;
}

.user-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 1.5rem;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 1rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-radius: 0.25rem;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-item .user-avatar {
  position: relative;
  margin-right: 1rem;
}

.user-item .status-dot {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border: 2px solid white;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 0.25rem;
}

.user-status {
  font-size: 0.75rem;
  color: #999;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式 */
.btn-primary {
  padding: 0.5rem 1rem;
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 0.25rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0e46c2;
}

.btn-primary:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-primary.small {
  padding: 0.375rem 0.75rem;
  font-size: 0.75rem;
}

.btn-outline {
  padding: 0.5rem 1rem;
  background-color: transparent;
  color: #165DFF;
  border: 1px solid #165DFF;
  border-radius: 0.25rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-outline:hover:not(:disabled) {
  background-color: #165DFF;
  color: white;
}

.btn-outline:disabled {
  border-color: #ccc;
  color: #ccc;
  cursor: not-allowed;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .chat-sidebar {
    width: 280px;
  }
  
  .message-content {
    max-width: 75%;
  }
}

@media (max-width: 640px) {
  .chat-layout {
    position: relative;
  }
  
  .chat-sidebar {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 100;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }
  
  .chat-sidebar.show {
    transform: translateX(0);
  }
  
  .chat-main,
  .chat-empty {
    width: 100%;
  }
}
</style>